package com.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class VolatleDemo {

    /**
     * volatile 关键字
     *  1.可见性  改变工作线程里面值后，主线程马上会同步（相当vue中双向绑定)
     *  2.禁止指令重排
     *  3.不保证原子性
     */
   volatile static int  count = 0;
   static AtomicInteger  ai = new AtomicInteger(0);

    static class  Thread1 extends  Thread
    {
        @Override
        public void run() {
            //count++;  //这个代码相当于下面2句
            //int x = count+1; //如果两个线程同时执行这句
            //count = x;

            count = ai.incrementAndGet();
        }
    }



    public static void main(String[] args) throws InterruptedException {
        ExecutorService es = Executors.newFixedThreadPool(1000);
        for (int i=1;i<=1000;i++)
        {
            es.execute(new Thread1());
        }
        es.shutdown(); //不接收新的线程加入线程池
        //等待线程池所有子线程执行完后，才执行下面代码，如果一分钟还没执行完也执行下面代码
        es.awaitTermination(1, TimeUnit.MINUTES);
        System.out.println(count);

    }

}
